package com.seari.vehbaseF.client;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seari.commonutils.redis.JedisUtilProxy;
import com.seari.commonutils.redis.ex.JedisNotInitializeException;
import com.seari.vehbaseF.util.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class RealDataHttpFetcher implements Runnable {

    protected Logger logger = LoggerFactory.getLogger(RealDataHttpFetcher.class);
    private String code;
    private String url;
    private int interval;
    private RealDataHttpStarter starter;

    public RealDataHttpFetcher(String code, String url, int interval,RealDataHttpStarter starter) {
        this.code = code;
        this.url = url;
        this.interval = interval;
        this.starter = starter;
    }

    @Override
    public void run() {
        Jedis jedis = null;
        String param = "ProjectCode=".concat(code);

        try {
            jedis = JedisUtilProxy.getJedis();
            Pipeline pipelined = jedis.pipelined();
            jedis.select(2);
            while (true) {
                String response = HttpClientUtil.getInstance().sendHttpPost(url, param);
                if (StringUtils.isNotBlank(response)) {
                    JSONObject responseObj = JSONObject.parseObject(response);

                    if (responseObj.containsKey("state") && responseObj.getInteger("state") == 0) {
                        JSONArray data = responseObj.getJSONArray("data");
                        Map<String, JSONArray> transferDataMap = new HashMap<>();

                        Iterator<Object> iterator = data.iterator();
                        String redisKey = "";
                        String previousId = "";

                        while (iterator.hasNext()) {

                            JSONObject element = (JSONObject) iterator.next();
                            String deviceID = element.getString("DeviceID");
                            if(StringUtils.isBlank(deviceID)){
                                continue;
                            }

                            element.put("projectCode",code);

                            if(!previousId.equals(deviceID)){
                                redisKey = StringUtils.join(code,"_",deviceID);
//                                redisKey = code.concat(deviceID);
                                previousId = deviceID;
                            }

                            JSONArray itemArray = transferDataMap.get(redisKey);
                            if (itemArray == null) {
                                transferDataMap.put(redisKey, new JSONArray().fluentAdd(element));
                            } else {
                                transferDataMap.replace(redisKey,itemArray.fluentAdd(element));
                            }
                        }

                        for (Map.Entry<String, JSONArray> jsonArrayEntry : transferDataMap.entrySet()) {
                            String redisValue = jsonArrayEntry.getValue().toJSONString();
                            pipelined.set(jsonArrayEntry.getKey(),redisValue);
                        }

                        pipelined.sync();

                        logger.info("Real-time data for project "+ code + " has been stored ..");

                    }
                }

                TimeUnit.SECONDS.sleep(interval);
            }

//
        } catch (JedisNotInitializeException e) {
            logger.error(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            if(null != jedis)
            {
                JedisUtilProxy.close(jedis);
            }
            starter.resetFetcher(this);
        }
    }

}
